<template>
  <ContainerGroup id="containerGroup">
    <Container>
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        :button-list="buttonList"
      />
    </Container>
    <Container height="fill" :scroll-y="true" display="flexY">
      <OperationContainer>
        <Button
          icon="edit"
          style="margin: 0"
          @click="_addItemHandle"
        >新增</Button>
      </OperationContainer>
      <el-table
        :data="tableData"
        border
        :header-cell-style="{ background: '#FAFAFA', height: '42px' }"
        stripe
        size="mini"
        highlight-current-row
        is-fill-height
        height="0"
        style="margin-top: 10px;margin-left: 5px;"
      >
        <el-table-column
          label="账号"
          prop="username"
          show-overflow-tooltip
        />
        <el-table-column
          label="工号"
          prop="employeeId"
          show-overflow-tooltip
        />
        <el-table-column
          label="姓名"
          prop="realname"
          show-overflow-tooltip
        />
        <el-table-column
          label="性别"
          prop="sexName"
          show-overflow-tooltip
        />
        <el-table-column
          label="科室"
          prop="deptName"
          show-overflow-tooltip
        />
        <el-table-column
          label="任职名称"
          prop="dutyName"
          show-overflow-tooltip
        />
        <el-table-column
          label="联系方式"
          prop="phone"
          show-overflow-tooltip
        />
        <el-table-column
          label="角色"
          prop="roleName"
          show-overflow-tooltip
        />
        <el-table-column
          label="账号状态"
          prop="enable"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div class="switchbox" @click="handleSwitch(scope.row)">
              <span :class="scope.row.enable === '0' ? 'spanactive' : '' " />
              <i class="switchafter" :class="scope.row.enable === '0' ? 'switchafteractive' : 'switchafteritem'" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="_editItemHandle(scope.row)">编辑</el-button>
            <el-button type="text" @click="_delItemHandle(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right;">
        <el-pagination
          :current-page.sync="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <Dialog
        :title="formtitle"
        :visible="dialogVisible"
        :footer-btns="[
          {
            text: '确定',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '关闭',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="_cancel('ruleForm')"
        @confirm="submitForm('ruleForm')"
      >
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-position="right" class="demo-ruleForm">
          <el-form-item label="账号" prop="username">
            <el-input v-model="ruleForm.username" size="mini" style="width:200px" />
          </el-form-item>
          <el-form-item label="工号" prop="employeeId">
            <el-input v-model="ruleForm.employeeId" size="mini" style="width:200px" />
          </el-form-item>
          <el-form-item label="姓名" prop="realname">
            <el-input v-model="ruleForm.realname" size="mini" style="width:200px" />
          </el-form-item>
          <el-form-item v-if="userstate === '1'" label="密码" prop="password">
            <el-input v-model="ruleForm.password" size="mini" style="width:200px" />
          </el-form-item>
          <el-form-item v-if="userstate === '2'" label="新密码" prop="newPassword">
            <el-input v-model="ruleForm.newPassword" size="mini" style="width:200px" />
          </el-form-item>
          <el-form-item v-if="userstate === '1'" label="确认密码" prop="confirmpwd">
            <el-input v-model="ruleForm.confirmpwd" size="mini" style="width:200px" />
          </el-form-item>
          <el-form-item label="性别" prop="sexCode">
            <el-select v-model="ruleForm.sexCode" placeholder="请选择性别" size="mini" style="width:200px" filterable clearable>
              <el-option label="男" value="1" />
              <el-option label="女" value="2" />
              <el-option label="未知" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="科室" prop="deptCode">
            <el-select v-model="ruleForm.deptCode" filterable placeholder="请选择科室" size="mini" style="width:200px" clearable>
              <el-option v-for="item in filterElements[5].options" :key="item.value" :label="item.label" :value="item.value + '-' + item.label" />
            </el-select>
          </el-form-item>
          <el-form-item label="任职名称" prop="dutyName">
            <el-input v-model="ruleForm.dutyName" size="mini" style="width:200px" />
          </el-form-item>
          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="ruleForm.phone" size="mini" style="width:200px" />
          </el-form-item>
          <el-form-item label="角色" prop="roleCode">
            <el-select v-model="ruleForm.roleCode" placeholder="请选择角色" size="mini" style="width:200px" filterable clearable>
              <el-option v-for="item in filterElements[2].options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属院区" prop="yard">
            <el-select v-model="ruleForm.yard" placeholder="请选择所属院区" size="mini" style="width:200px" filterable multiple clearable>
              <el-option v-for="item in regionoptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="账号状态" prop="enable">
            <el-select v-model="ruleForm.enable" placeholder="请选择账号状态" size="mini" style="width:200px">
              <el-option label="启用" value="0" />
              <el-option label="停用" value="1" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="账号状态" prop="enable">
            <div class="switchbox" @click="enableswith(ruleForm.enable)">
              <span :class="ruleForm.enable === '0' ? 'spanactive' : '' " />
              <i class="switchafter" :class="ruleForm.enable === '0' ? 'switchafteractive' : 'switchafteritem'" />
            </div>
          </el-form-item>
        </el-form>
      </Dialog>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  getListPage,
  delUser,
  getRolesList,
  getAllDeptList,
  addSysUser,
  getBySysUser,
  updateSysUser,
  editSysUser
} from '../../utils/apis/registrationApi'
export default {
  name: 'UserManagement', // 用户管理
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.confirmpwd !== '') {
          this.$refs.ruleForm.validateField('confirmpwd')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      tableColumns: [
        {
          title: '账号',
          width: '',
          dataIndex: 'username'
        },
        {
          title: '工号',
          width: '',
          dataIndex: 'employeeId'
        },
        {
          title: '姓名',
          dataIndex: 'realname',
          width: ' '
        },
        {
          title: '性别',
          dataIndex: 'sexName',
          width: '80'
        },

        {
          title: '科室',
          dataIndex: 'deptName',
          value: ''
        },
        {
          title: '任职名称',
          dataIndex: 'dutyName',
          width: '180'
        },
        {
          title: '联系方式',
          dataIndex: 'phone',
          value: ''
        },
        {
          title: '角色',
          dataIndex: 'roleName',
          value: ''
        },
        {
          title: '账号状态',
          type: 'switch',
          dataIndex: 'enable',
          width: '180',
          handlerClick: this._handleSwitch
        },
        {
          title: '操作',
          render: [
            {
              label: '编辑',
              type: 'primary',
              handlerClick: this._editItemHandle
            },

            {
              label: '删除',
              type: 'primary',
              handlerClick: this._delItemHandle
            }
          ]
        }
      ],
      buttonList: [
        {
          label: '查询',
          type: 'primary',
          handlerClick: this.handerSearch
        },
        {
          label: '重置',
          type: 'info',
          handlerClick: this._reset
        }
      ],

      filterElements: [
        {
          key: 'userName',
          type: 'Input',
          label: '账号',
          width: 260
        },

        {
          key: 'realName',
          type: 'Input',
          label: '姓名',
          width: 260
        },

        {
          key: 'roleCode',
          type: 'Select',
          label: '角色',
          value: '',
          options: [],
          width: 260
        },

        {
          key: 'enable',
          type: 'Select',
          label: '状态',
          value: '',
          width: 260,
          options: [
            {
              value: '0',
              label: '开启'
            },
            {
              value: '1',
              label: '关闭'
            }
          ]
        },
        {
          key: 'dutyName',
          type: 'Input',
          label: '任职名称',
          width: 260
        },
        {
          key: 'deptCode',
          type: 'Select',
          label: '科室',
          width: 260,
          value: '',
          options: []
        }
      ],
      dialogVisible: false,
      ruleForm: {
        deptCode:	'', // 科室编码
        deptName:	'', // 科室名称
        dutyName:	'', // 职务名称
        enable:	'1', // 0启用 1停用
        password:	'', // 密码
        confirmpwd: '', // 确认密码
        phone: '', // 电话
        realname:	'', // 真正名字
        roleCode:	'', // 角色ID
        sexCode: '', // 性别编码(1男 2女 0未知)
        username:	'', // 用户名
        employeeId: '', // 工号
        newPassword: '',
        yard: ''
        // enable1: false
      },
      rules: {
        dutyName: [{ required: true, message: '请输入职务名称', trigger: 'blur' }],
        password: [{ required: true, validator: validatePass, trigger: 'blur' }],
        confirmpwd: [{ required: true, validator: validatePass2, trigger: 'blur' }],
        phone: [{ required: true, message: '请填写手机号码', trigger: 'blur' }],
        realname: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
        username: [{ required: true, message: '请填写账号', trigger: 'blur' }],
        employeeId: [{ required: true, message: '请填写工号', trigger: 'blur' }],
        deptCode: [{ required: true, message: '请选择科室', trigger: 'change' }],
        roleCode: [{ required: true, message: '请选择角色', trigger: 'change' }],
        sexCode: [{ required: true, message: '请选择性别', trigger: 'change' }],
        yard: [{ required: true, message: '请选择所属院区', trigger: 'change' }]
      },
      userstate: '',
      pageNum: 1,
      number: '',
      name: '',
      status: '',
      role: '',
      roleList: [],
      sex: '',
      dept: '',
      deptList: [],
      total: 0,
      pageSize: 20,
      currentPage: 1,
      tableData: [],
      queryList: {},
      userId: '',
      formtitle: '新增用户',
      regionoptions: [
        {
          value: '1',
          label: '三香院区'
        },
        {
          value: '2',
          label: '浒关院区'
        }
      ]
    }
  },
  mounted() {
    this._getData()
    this._getroleList()
  },
  methods: {
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this._getData()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this._getData()
    },
    dialogConfirm() {},
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = { ...this.ruleForm }
          const arr = params.deptCode.split('-')
          params.deptCode = arr[0]
          params.deptName = arr[1]
          const yardArr = params.yard.join(',')
          if (this.userstate === '1') {
            delete params.confirmpwd
            delete params.newPassword
            params.yard = yardArr
            addSysUser(params).then((res) => {
              if (res.data.code === 200) {
                this.$message.success(res.data.data)
                this._getData()
                this.dialogVisible = false
                this.$refs[formName].resetFields()
              } else {
                this.$message.error(res.data.message)
                this.$refs[formName].resetFields()
              }
            })
          } else if (this.userstate === '2') {
            delete params.confirmpwd
            params.userId = this.userId
            params.yard = yardArr
            updateSysUser(params).then((res) => {
              if (res.data.code === 200) {
                this.$message.success(res.data.data)
                this._getData()
                this.dialogVisible = false
                this.$refs[formName].resetFields()
              } else {
                this.$message.error(res.data.message)
                this.$refs[formName].resetFields()
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    _cancel(formName) {
      this.dialogVisible = false
      this.$refs[formName].resetFields()
    },
    // 删除
    _delItemHandle(row) {
      this.$confirm({
        content: '是否确认删除该用户？',
        title: '温馨提示',
        okFn: (res) => {
          delUser({ id: row.userId }).then((res) => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this._getData()
            }
          })
        },
        cancelFn: (res) => {
          console.log('取消')
        }
      })
    },
    // 查询
    handerSearch(val) {
      this.queryList = val
      this._getData()
    },
    // 获取用户列表
    _getData() {
      let params
      if (JSON.stringify(this.queryList) === '{}') {
        params = {
          deptCode: '', // 部门编码
          dutyName: '', // 任职编码
          enable: '', // 状态 0 开启 1 关闭
          realName: '', // 真实姓名
          roleCode: '', // 角色编码
          userName: '', // 用户名
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
      } else {
        params = {
          deptCode: this.queryList.deptCode === undefined ? '' : this.queryList.deptCode, // 部门编码
          dutyName: this.queryList.dutyName === undefined ? '' : this.queryList.dutyName, // 任职编码
          enable: this.queryList.enable === undefined ? '' : this.queryList.enable, // 状态 0 开启 1 关闭
          realName: this.queryList.realName === undefined ? '' : this.queryList.realName, // 真实姓名
          roleCode: this.queryList.roleCode === undefined ? '' : this.queryList.roleCode, // 角色编码
          userName: this.queryList.userName === undefined ? '' : this.queryList.userName, // 用户名
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
      }
      getListPage(params).then((res) => {
        if (res.status === 200) {
          this.tableData = res.data.data.list
          this.tableData.forEach((element) => {
            if (element.sexCode === '1') {
              element.sexName = '男'
            } else if (element.sexCode === '2') {
              element.sexName = '女'
            } else {
              element.sexName = ''
            }
          })
          this.total = res.data.data.total
        }
      })
    },
    // 获取角色，科室列表
    _getroleList() {
      getRolesList().then((res) => {
        if (res.status === 200) {
          res.data.data.forEach(item => {
            const obj = {
              label: item.roleName,
              value: item.roleId
            }
            this.filterElements[2].options.push(obj)
          })
        }
      })
      getAllDeptList({}).then((res) => {
        if (res.status === 200) {
          res.data.data.forEach(item => {
            const obj = {
              label: item.deptName,
              value: item.deptCode
            }
            this.filterElements[5].options.push(obj)
          })
        }
      })
    },
    // 新增用户
    _addItemHandle() {
      this.dialogVisible = true
      this.userstate = '1'
      this.formtitle = '新增用户'
    },
    // 编辑用户
    _editItemHandle(row) {
      this.formtitle = '编辑用户'
      this.dialogVisible = true
      this.userstate = '2'
      getBySysUser({ userId: row.userId }).then((res) => {
        if (res.data.code === 200) {
          const form = res.data.data
          this.ruleForm = {
            deptCode:	form.deptCode + '-' + form.deptName, // 科室编码
            deptName:	'', // 科室名称
            dutyName:	form.dutyName, // 职务名称
            enable:	form.enable, // 0启用 1停用
            password:	'', // 密码
            confirmpwd: '', // 确认密码
            newPassword: form.newPassword,
            phone: form.phone, // 电话
            realname:	form.realname, // 真正名字
            roleCode:	form.roleCode, // 角色ID
            sexCode: form.sexCode, // 性别编码(1男 2女 0未知)
            username:	form.username, // 用户名
            employeeId: form.employeeId,// 工号
            yard: form.yard?.split(',') // 所属院区
          }
          // console.log('this.ruleForm', this.ruleForm);
          this.userId = form.userId
        }
      })
    },
    _reset() {
      this.$refs.filterForm.reset()
    },
    handleSwitch(row) {
      if (row.enable === '0') {
        row.enable = '1'
      } else {
        row.enable = '0'
      }
      editSysUser({ userId: row.userId, enable: row.enable }).then((res) => {
        if (res.data.code === 200) {
          // console.log(res.data)
        }
      })
    },
    enableswith(enable) {
      if (enable === '0') {
        this.ruleForm.enable = '1'
      } else {
        this.ruleForm.enable = '0'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.demo-ruleForm{
  width: 600px;
  // display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.el-table {
    /deep/ th {
      padding: 0 ;
      height: 40px;
      background-color: #F5F7FA;
    }
    /deep/ td {
      padding: 0 ;
      height: 44px;
      /deep/ button{
        font-size: 14px;
      }
      /deep/ input{
        height: 28px;
      }
      /deep/ .el-select__caret{
        line-height: 28px;
      }
    }
}
.switchbox{
  display: inline-flex;
  align-items: center;
  position: relative;
  font-size: 14px;
  line-height: 20px;
  height: 20px;
  vertical-align: middle;
  span{
    margin: 0;
    position: relative;
    width: 40px;
    height: 20px;
    outline: 0;
    border-radius: 10px;
    box-sizing: border-box;
    background: #DCDFE6;
    transition: border-color .3s,background-color .3s;
    vertical-align: middle;
    display: inline-block;
    cursor: pointer;
  }
  .switchafter{
    position: absolute;
    top: 2px;
    border-radius: 100%;
    transition: all .3s;
    width: 16px;
    height: 16px;
    background-color: #FFF;
  }
  .spanactive{
    background: #FFA712;
  }
  .switchafteractive{
    left: 55%;
  }
  .switchafteritem{
    left: 1.5px;
  }
}
</style>
